const { DataTypes } = require('sequelize');

module.exports = (sequelize) => {
  const Coupon = sequelize.define('Coupon', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    title: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '优惠券标题'
    },
    price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      comment: '优惠券价格'
    },
    duration: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '抵扣时长(小时)'
    },
    expireDate: {
      type: DataTypes.DATEONLY,
      allowNull: false,
      field: 'expire_date',
      comment: '过期日期'
    },
    terms: {
      type: DataTypes.TEXT,
      comment: '使用条款'
    },
    isTemplate: {
      type: DataTypes.BOOLEAN,
      defaultValue: true,
      field: 'is_template',
      comment: '是否为模板券：true-是，false-否'
    },
    stock: {
      type: DataTypes.INTEGER,
      defaultValue: -1,
      comment: '库存数量，-1表示不限，仅模板券有效'
    },
    periodLimit: {
      type: DataTypes.STRING(50),
      field: 'period_limit',
      comment: '时段限制，如日场/夜场'
    },
    userId: {
      type: DataTypes.INTEGER,
      field: 'user_id',
      allowNull: true,
      comment: '购买用户ID，NULL表示模板券'
    },
    remainTimes: {
      type: DataTypes.INTEGER,
      defaultValue: 1,
      field: 'remain_times',
      comment: '剩余可用次数'
    },
    status: {
      type: DataTypes.TINYINT,
      defaultValue: 1,
      comment: '券状态：0-已使用/下架，1-未使用/正常'
    },
    templateId: {
      type: DataTypes.INTEGER,
      field: 'template_id',
      allowNull: true,
      comment: '关联的模板券ID'
    },
    purchaseTime: {
      type: DataTypes.DATE,
      field: 'purchase_time',
      allowNull: true,
      comment: '购买时间'
    },
    verifyCode: {
      type: DataTypes.STRING(50),
      field: 'verify_code',
      allowNull: true,
      comment: '核销码'
    },
    roomType: {
      type: DataTypes.STRING(50),
      field: 'room_type',
      allowNull: true,
      comment: '可预订房间类型'
    }
  }, {
    tableName: 'coupons',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  });

  // 设置关联关系
  Coupon.associate = (models) => {
    // 用户关联
    Coupon.belongsTo(models.User, { 
      foreignKey: 'user_id',
      as: 'user'
    });
    
    // 模板券关联 (自关联)
    Coupon.belongsTo(Coupon, { 
      as: 'template', 
      foreignKey: 'template_id'
    });
    
    Coupon.hasMany(Coupon, { 
      as: 'instances', 
      foreignKey: 'template_id'
    });
  };

  return Coupon;
}; 